package com.lagou.edu;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class RequestProcessor extends Thread{

    private Socket accept;
    private Map<String,HttpServlet> servletMap;

    private Map<String,Wrapper> contextMap = new HashMap<>();
//    public RequestProcessor(Socket socket, Map<String,HttpServlet> servletMap){
//        this.accept = socket;
//        this.servletMap = servletMap;
//    }

    public RequestProcessor(Socket socket, Map<String,Wrapper> contextMap){
        this.accept = socket;
        this.contextMap = contextMap;
    }

//    @Override
//    public void run() {
//        InputStream inputStream = null;
//        try {
//            inputStream = accept.getInputStream();
//            OutputStream outputStream = accept.getOutputStream();
//            Request request = new Request(inputStream);
//            Response response = new Response(outputStream);
//            if(servletMap.get(request.getUrl()) == null){
//                response.outHtml(request.getUrl());
//            }else{
//                HttpServlet httpServlet = servletMap.get(request.getUrl());
//                httpServlet.service(request,response);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }finally {
//            try {
//                accept.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//    }

    @Override
    public void run() {
        InputStream inputStream = null;
        try {
            inputStream = accept.getInputStream();
            OutputStream outputStream = accept.getOutputStream();
            Request request = new Request(inputStream);
            Response response = new Response(outputStream);
            int i = request.getUrl().indexOf("/", 2);
            String substring = request.getUrl().substring(1, i);


            if(contextMap.get(substring) == null){
                response.outHtml(request.getUrl());
            }else{
                Wrapper wrapper = contextMap.get(substring);
                if(wrapper.getUrl().equals( request.getUrl().substring(i))){
                    wrapper.getHttpServlet().service(request,response);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                accept.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
